// 顺时针打印螺旋式矩阵

function matrix(val){
  let target = []
  let counter = val+1 // 判断每次循环什么时候转向
  let addCount = val // 每组数据要添加的个数
  let group = 1 // 第几组数据，或者说第几次转向
  let counterChangeFlag = 1 // 每循环两组数据，counter要-1
  let arrColumn = 0 // 初始列值
  let arrRow = 0 // 初始行值
  // 初始化数组容器
  for(let i = 0; i<val; i++){
    target.push([])
  }
  for(let i = 0; i < val*val; i++){
    counter = counter - 1
    if(counter == 0){
      group = group + 1
      counter = addCount
      counterChangeFlag = counterChangeFlag + 1
      if(counterChangeFlag == 2){
        counterChangeFlag = 0
        addCount = addCount - 1
        counter = addCount
      }
    }
    let fx =  group % 4 == 1 ? 'right' : group % 4 == 2 ? 'down' : group % 4 == 3 ? 'left' : 'up'
    console.log(`第${fx}组${i+1}`)
    switch (fx) {
      case 'right':
        arrColumn += 1
        target[arrRow][arrColumn-1] = i+1
        break;
      case 'down':
        arrRow ++
        target[arrRow][arrColumn-1] = i+1
        break;
      case 'left':
        arrColumn--
        target[arrRow][arrColumn-1] = i+1
        break
      case 'up':
        arrRow--
        target[arrRow][arrColumn-1] = i+1
        break
      default:
        break;
    }
  }
  
  return target
}
matrix(11)